package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.Question;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TodayBestService {

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private QuestionApi questionApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private UserLocationApi userLocationApi;

    @DubboReference
    private VisitorsApi visitorsApi;
    @DubboReference
    private UserLikeApi userLikeApi;
    @DubboReference
    private FriendsApi friendsApi;


    //今日佳人
    public TodayBest todayBest() {
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        //2、调用RecommendUserApi查询推荐数据   RecommendUser（userId,toUserId,Score）
        RecommendUser user = recommendUserApi.queryWithMaxScore(userId);
        //3、根据推荐用户ID，查询用户资料  UserInfo
        UserInfo userInfo = userInfoApi.findById(user.getUserId());
        //4、将UserInfo转化为TodayBest
//        TodayBest vo = new TodayBest();
//        BeanUtils.copyProperties(userInfo,vo);
//        if(userInfo.getTags()!= null) {
//            vo.setTags(userInfo.getTags().split(","));
//        }
//        vo.setFateValue(user.getScore().longValue());
        return TodayBest.init(userInfo,user);
    }

    //查询推荐的今日佳人分页列表  ***
    public PageResult recommendation(RecommendUserDto dto) {
        //1、获取参数 （当前用户id，page，pagesize）
        Long userId = UserHolder.getUserId();
        //2、调用recommendUserApi分页查询推荐用户列表 PageResult<RecommendUser列表>
        PageResult pr = recommendUserApi.queryRecommendUserList(userId,dto.getPage(),dto.getPagesize());
        //3、获取分页的数据列表 ： RecommendUser列表
        List<RecommendUser> items = (List<RecommendUser>) pr.getItems();
        if(CollUtil.isEmpty(items)) {
            return pr;
        }
        //4、一个RecommendUser封装成一个TodayBest对象
        //从list集合中提取对象中的某个属性，作为集合
        List<Long> userIds = CollUtil.getFieldValues(items,"userId",Long.class);

        //查询一次UserInfo获取所需的用户 Map<UserId,UserInfo>    1,2,3,4,5,6
        UserInfo params = new UserInfo();
        params.setAge(dto.getAge());  //20
        params.setGender(dto.getGender());  //man

        Map<Long,UserInfo> map = userInfoApi.findByIds(userIds,params);

        List<TodayBest> vos = new ArrayList<>();
        for (RecommendUser item : items) {
            Long id = item.getUserId();
            UserInfo userInfo = map.get(id);
            if(userInfo != null) {
                TodayBest vo = TodayBest.init(userInfo, item);
                vos.add(vo);
            }
        }
        //
        //5、返回
        pr.setItems(vos); //替换pageresult中的items列表（recommendUser -- todayBest）
        return pr;
    }


    //使用手机的人：106
    //查看的感兴趣的人：2号

    //佳人详情
    public TodayBest personalInfo(Long userId) {
        //1、查询目标用户的资料
        UserInfo userInfo = userInfoApi.findById(userId);
        //2、查询目标用户和当前操作人的缘分值
        RecommendUser ru = recommendUserApi.queryByUserId(userId,UserHolder.getUserId());
        //记录访客信息
        Visitors visitors = new Visitors();
        visitors.setUserId(userId);
        visitors.setVisitorUserId(UserHolder.getUserId());
        visitors.setFrom("首页");
        visitors.setScore(ru.getScore()); //设置缘分值
        visitors.setDate(System.currentTimeMillis());
        visitors.setVisitDate(new SimpleDateFormat("yyyy/MM/dd").format(new Date()));
        visitorsApi.save(visitors);
        //3、构造vo对象
        return TodayBest.init(userInfo,ru);
    }

    //查询指定用户设置的陌生人问题
    public String strangerQuestions(Long userId) {
        Question question = questionApi.findByUserId(userId);
        return question == null ? "你喜欢java吗？":question.getTxt();
    }

    //对方的用户id
    public void relayStrangerQuestions(Long userId, String reply) {
        //1、构造发送的数据
        Map map = new HashMap();
        //设置发起申请的用户id和环信id
        map.put("userId",UserHolder.getUserId());
        //设置发起申请的用户名称
        map.put("huanXinId","hx"+UserHolder.getUserId());
        UserInfo info = userInfoApi.findById(UserHolder.getUserId());
        map.put("nickname",info.getNickname());
        //陌生人问题
        map.put("strangerQuestion",strangerQuestions(userId));
        //回复的内容
        map.put("reply",reply);
        //转化为JSON
        String message = JSON.toJSONString(map);
        //2、调用工具类，发送消息
        Boolean aBoolean = huanXinTemplate.sendMsg("hx" + userId, message);
        if(!aBoolean) {
            throw new BusinessException(ErrorResult.error());
        }
    }

    //搜附近
    public List<NearUserVo> searchNear(String gender, String distance) {
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        //2、调用API查询，查询附近的人所有ID即可
        List<Long> userIds = userLocationApi.findByUserId(userId,Long.valueOf(distance));
        //3、查询用户信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //4、构造返回值
        List<NearUserVo> vos = new ArrayList<>();
        for (Long id : userIds) {
            if(id == UserHolder.getUserId()) {
                //自己
                continue;
            }
            UserInfo info = map.get(id);
            if(!info.getGender().equals(gender)) {
                continue;
            }
            if(info != null) {
                NearUserVo vo = NearUserVo.init(info);
                vos.add(vo);
            }
        }
        return vos;
    }

    /**
     *
     * @return
     */
//随机获取10个用户推荐列表里面的对应的用户
    public List<TodayBest> cards() {
        //随机查询10条recommenduser

        List<RecommendUser>list=recommendUserApi.randomRecommendUser(UserHolder.getUserId(),10);
        //获取list集合里面对应的ids查询对应的userinfo，构建todaybest
        List<Long> ids = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids,null);
        List<TodayBest>todayBests=new ArrayList<>();
        for (RecommendUser recommendUser : list) {
            UserInfo userInfo = map.get(recommendUser.getUserId());
            if(userInfo!=null){
                TodayBest init = TodayBest.init(userInfo, recommendUser);

                todayBests.add(init);
            }
        }

        return todayBests;
    }

    /**
     * 喜欢保存到userlike表
     * 并且删除recommenduser表中的数据
     * 如果说他是我的粉丝这直接添加好友，关系
     * 参数是对象的id
     */
    public void love(Long id) {
        //保存到数据库中

        UserLike userLike=new UserLike();
        userLike.setUserId(UserHolder.getUserId());
        userLike.setLikeUserId(id);
        userLike.setIsLike(true);
        userLikeApi.save (userLike);
        //删除recommenduser表中的数据
        recommendUserApi.delete(UserHolder.getUserId(),id);


        //查询表中该用户是否是粉丝，如果是，添加好友，添加换新好友关系
        //查询对方是否喜欢我，则userid为id，likeuserid=用户id
        Boolean b=userLikeApi.fan(id,UserHolder.getUserId());
        //如果存在则添加好友关系，添加环信好友
        if(b){
            friendsApi.save(UserHolder.getUserId(),id);
            huanXinTemplate.addContact("hx"+UserHolder.getUserId(),"hx"+id);

        }
    }
    /**
     * 不喜欢也保存到userlike表
     * 并且删除recommenduser表中的数据
     * 如果说他是我的粉丝这直接删除好友关系
     *      * 参数是对象的id
     */
    public void unLove(Long id) {

        //保存到数据库中
        UserLike userLike=new UserLike();
        userLike.setUserId(UserHolder.getUserId());
        userLike.setLikeUserId(id);
        userLike.setIsLike(false);
        userLikeApi.save(userLike);
        //删除recommenduser表中的数据
        recommendUserApi.delete(UserHolder.getUserId(),id);
    }



}

